package up7.biz.folder;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import com.google.gson.Gson;

import up7.database.DbHelper;
import up7.model.FileInf;
import up7.database.sql.SqlFile;
import up7.sql.SqlExec;
import up7.sql.SqlTable;
import up7.sql.SqlWhere;
import up7.sql.SqlWhereMerge;
import down3.model.DnFileInf;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

//文件夹读取分页数据
public class fd_page 
{
	/**
	 * 
	 * @param pageIndex 页索引，基于1
	 */
	public String read(String pageIndex,String id) throws ParseException, IllegalAccessException, SQLException {
		Integer pageSize = 100;//每页100条数据
		Integer index = Integer.parseInt(pageIndex);
		SqlWhereMerge swm = new SqlWhereMerge();
		swm.equal("f_pidRoot", id);
		
		FileInf s = SqlTable.build("up7_files").readOne(FileInf.build(),
				SqlWhere.build().eq("f_id",id));
		//子目录
        if(s == null) s = SqlTable.build("up7_folders").readOne(FileInf.build(),
				SqlWhere.build().eq("f_id",id));
        
        String pathRoot = s.pathRel;
        int dirLen = pathRoot.length();
		
		SqlExec se = new SqlExec();
		JSONArray data = se.page("up7_files"
				, "f_id"
				, "f_id,f_nameLoc,f_pathLoc,f_pathSvr,f_pathRel,f_blockPath,f_blockSize,f_lenLoc,f_sizeLoc,f_object_url"
				, pageSize
				, Integer.parseInt( pageIndex )
				, swm.to_sql()
				, "");

        List<DnFileInf> files = new ArrayList<DnFileInf>();
		for(int i = 0 ,l=data.size(); i<l; ++i)
		{
			JSONObject o = (JSONObject)data.get(i);

			DnFileInf f = new DnFileInf();
        	String uuid = UUID.randomUUID().toString();
        	uuid = uuid.replace("-", "");

        	f.id 		= uuid;
        	f.f_id 		= o.getString("f_id");
        	f.nameLoc 	= o.getString("f_nameLoc");
        	//f.pathLoc 	= o.getString("f_pathLoc");
        	f.pathSvr 	= o.getString("f_pathSvr");
        	f.pathRel 	= o.getString("f_pathRel");
        	f.pathRel   = f.pathRel.substring(dirLen);
        	//f.blockPath = o.getString("f_blockPath");
        	f.blockSize = o.getInt("f_blockSize"); 
        	f.lenSvr 	= o.getLong("f_lenLoc");
        	f.sizeSvr 	= o.getString("f_sizeLoc");
        	f.objectUrl = o.getString("f_object_url");
        	files.add(f);
		}
		
		Gson gson = new Gson();
		return gson.toJson(files);
	}
}
